<template>
  <div>
    <el-dialog
      :title="formData.id?'编辑员工':'添加员工'"
      :visible="dialogVisible"
      @close="closeFn"
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item v-if="!formData.id" label="密码" prop="password">
          <el-input v-if="!formData.id" v-model="formData.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="small" @click="submit">确定</el-button>
          <el-button size="small" @click="closeFn">取消</el-button>
        </el-row>

      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getEmployeeById, addEmployee, editEmployee } from '@/api/employee/index'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {

      formData: {
        username: '',
        email: '',
        password: ''

      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
        ]

      }
    }
  },
  methods: {
    async getEmployeeById(id) {
      const res = await getEmployeeById(id)
      console.log(62, res)
      this.formData = res.data
    },
    async submit() {
      await this.$refs.form.validate()
      if (this.formData.id) {
        await editEmployee(this.formData)
      } else {
        await addEmployee(this.formData)
      }

      this.closeFn()
      this.$emit('updateEvent')
    },
    closeFn() {
      this.$emit('update:dialogVisible', false)
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
